/*
 * @Author: TC
 * @Date: 2025-05-29 10:10:17
 * @Last Modified by: TC
 * @Last Modified time: 2025-05-29 10:14:42
 */

import fs, { createReadStream, createWriteStream } from "fs";
import path from "path";
import { pipeline } from "stream/promises";
export class FileUtil {
    /**
     * 拷贝单个文件
     */
    static copyFile(sourcePath: string, targetPath: string, overwrite: boolean = true, cb?: () => void): void {
        // 检查源文件是否存在
        try {
            const stats = fs.statSync(sourcePath);
            if (!stats.isFile()) {
                throw new Error(`源路径 '${sourcePath}' 不是文件`);
            }
        } catch (error) {
            throw new Error(`源文件不存在: ${sourcePath}`);
        }

        // 检查目标文件是否存在
        if (!overwrite) {
            try {
                fs.statSync(targetPath);
                throw new Error(`目标文件已存在: ${targetPath}`);
            } catch (error: any) {
                if (error.code !== "ENOENT") {
                    throw error;
                }
            }
        }

        // 创建目标文件所在目录（如果不存在）
        const targetDir = path.dirname(targetPath);
        fs.mkdirSync(targetDir, { recursive: true });

        // 拷贝文件内容
        pipeline(createReadStream(sourcePath), createWriteStream(targetPath)).then(() => {
            if (cb) cb();
        });
    }
}
